<?php

namespace app\admin\controller;

use app\common\controller\Backend;

class Index extends Backend
{
    public function index()
    {
        $navTitle = '后台首页';
        return $this->fetch('', [
            'navTitle' => $navTitle
        ]);
    }

    // 后台登录功能
    public function login()
    {
        $LoginAdmin = !empty(cookie('LoginAdmin')) ? cookie('LoginAdmin') : '';
        if ($LoginAdmin) {
            $adminList = model('Admin')->select();
            $adminid = 0;
            foreach ($adminList as $item) {
                $val = md5($item['id'] . $item['salt']);
                if ($LoginAdmin == $val) {
                    $adminid = $item['id'];
                    break;
                }
            }
            $admin = model('Admin')->find($adminid);
            if (!$admin) {
                cookie('LoginAdmin', null);
                $this->error('非法登录', url('admin/index/login', null, 2));
            }
            if ($admin['state'] == 0) {
                cookie('LoginAdmin', null);
                $this->error('该账号被禁用，请联系管理员', null, null, 1.5);
            }
            $this->success('您已登录，无需重复操作', url('admin/index/index'), null, 2);
        }

        if ($this->request->isPost()) {
            $params = $this->request->param();
            if (!captcha_check($params['captcha'])) {
                $this->error('验证码错误', null, null, 2);
            }

            $admin = model('Admin')->where('username', $params['username'])->find();
            if (!$admin) {
                $this->error('管理员不存在', null, null, 2);
            }
            $pwd = md5($params['password'] . $admin['salt']);
            if ($pwd != $admin['password']) {
                $this->error('密码错误', null, null, 2);
            }
            if ($admin['state'] == 0) {
                cookie('LoginAdmin', null);
                $this->error('该账号被禁用，请联系管理员', null, null, 2);
            }

            if (!empty($params['rememberme']) && $params['rememberme'] == 1) {
                cookie('LoginAdmin', md5($admin['id'] . $admin['salt']), 5 * 24 * 3600 + time());
            } else {
                cookie('LoginAdmin', md5($admin['id'] . $admin['salt']));
            }

            $this->success('登录成功', url('admin/index/index'), null, 2);
        }


        // 动态使用模板布局
        $this->view->engine->layout(false);
        return $this->fetch();
    }

    // 后台退出登录功能
    public function logout() {
        cookie('LoginAdmin' , null);
        $this->success('退出成功', url('admin/index/login'), null, 2);
    }
}
